<?php

/**
 * Created by PhpStorm.
 * User: shwy
 * Date: 2017/6/2
 * Time: 16:58
 * 采购管理
 */

class Procurement extends MY_Controller {

	// 使用构造函数, 必须先使用父级的构造函数
	public function __construct() {
		parent::__construct();
		$this->load->model('procurement_model');
		$this->load->model('purchaseOrder_model');
		$this->load->model('stockPut_model');
		$this->load->model('stockOut_model');

		$this->load->model('returnOrder_model');
		
		$this->load->model('check_model');
		$this->load->model('goodsStockPrice_model');
		$this->load->model('project_model');
		$this->load->model('supplier_model');

		$this->load->model('biddingconfirm_model');

//        $this->load->model('bidding_model');

		$this->load->library('Qiniu');

	}

	/**
	 *
	 * 点击新增需求单，进入新增需求单页面   已完成
	 * 点击需求单编号，进入需求单详情页     已完成
	 * 所以的需求单在未进行进货前都可以作废，点击作废，状态变为已作废   下午增加是否开始进货了
	 * 审核通过的采购需求单，点击去进货，进入采购进货单页面
	 * 未提交的需求单可以进行再次编辑，点击编辑，进入采购需求单编辑页面   判断是否提交
	 * 采购需求单未提交前，可以删除，提交后只能进行作废            判断是否提交
	 * 当前页面数据超过20条时，翻页显示     已完成
	 */

	// todo  采购管理中的招投标项目删除,招投标删除中关联的数据是否要删除

// 采购需求单---------------------------------------------------------
	// 采购管理
	public function index() 
	{
		$page_num = $this->config->item('fenye')['pageNum']; //每页的数据
		$start_position = 0; //初始数据
		$page = ($this->input->get('page')); //获取页码数量
		if ($page) {
			$start_position = ($page - 1) * $page_num;
		}

		$where = [
			'type !=' => '采购项目单',
		];
		$data = $this->procurement_model->page('procurement', $where, $page_num, $start_position); 
		
		if ($data[0]) {
			$viewData = [
				'list' 	   => $data[0], 		  // 这里得到从数据库中的当页数据
				'totalNum' => $data['total_num'], // 这里得到从数据库中的总页数
				'pageNum'  => $page_num, 		  // 每页显示多少条
			];
		} else {
			$viewData = [
				'list' => '', 
				'totalNum' => $data['total_num'], 
				'pageNum' => $page_num, 
			];
		}
		$this->load->view('admin/procurement/list', $viewData);
	}
	
	// 新增采购需求页面
	public function addView() 
	{
		// 添加项目列表
		$data['project'] = $this->project_model->getData('id, name', 1);
		$this->load->view('/admin/procurement/add', $data);
	}
	
	// 新增采购需求单功能 与 采购项目单同一方法
	public function add() 
	{
		$post = $this->input->post();	
		$data = [
			'needCode' 	 => trim($post['needCode']),			// 需求单号
			'source' 	 => $post['source'],					// 所属项目
			'endTime' 	 => trim(strtotime($post['endTime'])),	// 发起时间
			'content' 	 => trim($post['content']),				// 申请原因
			
			'name' 		 => trim($post['name']),				// 需求单名称
			'contactMan' => trim($post['contactMan']),			// 发起人
			'createTime' => strtotime($post['createTime']), 	// 期望时间
			'type' 		 => $post['type'],						// 需求单类型
			
			'attribute' 	=> $post['attribute'],		// 商品属性
			'amount' 		=> $post['amount'],			// 总金额
			'goodsMessage' 	=> $post['goodsMessage'], 	// 商品信息
			
			'manager'    => $post['manager'],			// 一级审批人, 部门主管
			'safeguard'  => $post['safeguard'],			// 二级审批人, 保障中心总监
			'deputy' 	 => $post['deputy'],			// 三级审批人, 分管副总
			'fdeputy' 	 => $post['fdeputy'], 			// 四级审批人, 财务分管副总
			'chairman' 	 => $post['chairman'],			// 五级审批人, 董事长			
			'financial'  => $post['financial']			// 审批抄送人																
		];
	
		if ($post['action'] == '提交') {
			// 状态为1 审核中
			$data['status'] = 1;
		} else {
			// 状态为0 待提交
			$data['status'] = 0;
		}
		
		$insertId = $this->procurement_model->addId($data);
		if (!$insertId) {
			echo '数据错误, 请重新提交';
			exit;
		}
		// 若插入成功, 且点击的是提交按钮, 则开始进行审核
		if ($data['status'] == 1) {				
			// 添加审核管理里面
				// 根据总金额判断审核层级	
			$amount = $post['amount'];
			if ($amount > 0) {
					if ($amount > 0 && $amount <= 100000) {
						$num = 3;
					} else if ($amount > 100000 && $amount <= 500000) {
						$num = 4;
					} else if ($amount > 500000) {
						$num = 5;
					}	
				} else {
					echo '金额必须有效';
					exit;
				}
			switch ($post['type']) {				
					case '普通需求单':
					$type = 1;
					break;
				
				case '招投标项目需求单':
					$type = 2;
					break;
				
				case '采购项目单':
					$type = 3;
					break;
					
				case '采购退货单':
					$type = 5;
					break;
				
				case '采购换货单':
					$type = 6;
					break;
									
				default:
					$type = 10;
					break;
			}
			$checkData = [
				'type' 			=> $type,
				'relevanceId' 	=> $insertId, //返回主键id
				'checkinfo' 	=> '',
				'checker' 		=> $post['manager'],
				'status' 		=> 0,
				'checkStatus' 	=> 0,
				'howLevelCheck' => $num,
				'createTime' 	=> time(),
				'checkOrderType'=> $post['type'],
			];
			$res = $this->check_model->add($checkData);
		} else {
			echo '暂存成功';
			exit;
		}
		if ($res) {
			echo '提交成功';
		} else {
			echo '数据错误, 请查看, 并重新提交';
		}
	}
	
	// 采购需求单编辑页面
	public function editView() 
	{
		// 读取用户名根据get id
		$arg = [
			'id' => $this->input->get('id'),
		];
		$data['list'] = $this->procurement_model->getByFieldQueryData('*', $arg, 0);

		// 如果不存在直接跳转到404页面
		if (!$data['list']) {
			redirect('/home/error');
		}

		$data['list']['goodsMessage'] = json_decode($data['list']['goodsMessage'], true);
		if ($data['list']['goodsMessage']) {
			// 根据商品id查询商品数据
			foreach ($data['list']['goodsMessage'] as $k => $v) {
				if (isset($v['dataId'])) {
					$arg = [
						'product_id' => $v['dataId'],
					];
				} else {
					$data['list']['goodsMessage'][$k]['dataId'] = '';
				}

				$isStock = $this->goodsStockPrice_model->getByFieldQueryData($fields = '*', $arg, $isMore = 0);
			}
			// 查询是否有库存
			foreach ($data['list']['goodsMessage'] as $k2 => $v2) {
				$arg2 = [
					'product_id' => $v2['dataId'],
				];

				$isStock[] = $this->goodsStockPrice_model->getByFieldQueryData($fields = 'id,product_id,specification_group_names', $arg2, 0);
			}
			
			foreach ($data['list']['goodsMessage'] as $k4 => $v4) {
				# code...

				if ($v4['specification']) {
					$data['list']['goodsMessage'][$k4]['isStock'] = 1;
				} else {
					$data['list']['goodsMessage'][$k4]['isStock'] = 0;
				}
			}
		}
		
		if ($data['list']['endTime'] === '0') {
			$data['list']['endTime'] = '请选择时间';
		} else {
			$data['list']['endTime'] = date('Y-m-d', $data['list']['endTime']);
		}

		$data['project'] = $this->project_model->getData('id,name', 1);
		
		$this->load->view('/admin/procurement/edit', $data);
	}
	
	// 采购需求单编辑功能
	public function edit() 
	{
		$post = $this->input->post();	
		$data = [
			'source' 		=> $post['source'],	// 所属项目
			'content' 		=> trim($post['content']),	// 申请原因
			'name' 			=> trim($post['name']),		// 需求单名称
			'contactMan' 	=> trim($post['contactMan']),	// 发起人
			
			'manager'   	=> $post['manager'],	// 一级审批人, 部门主管
			'safeguard' 	=> $post['safeguard'],	// 二级审批人, 保障中心总监
			'deputy' 		=> $post['deputy'],		// 三级审批人, 分管副总
			'fdeputy' 		=> $post['fdeputy'], 	// 四级审批人, 财务分管副总
			'chairman' 		=> $post['chairman'],	// 五级审批人, 董事长			
			'financial' 	=> $post['financial'],	// 审批抄送人
			
			'endTime' 		=> trim(strtotime($post['endTime'])),	// 发起时间
			'createTime' 	=> trim(strtotime($post['createTime'])),// 期望时间
					
			'attribute' 	=> $post['attribute'],	// 商品属性
			'amount' 		=> $post['amount'],		// 总金额
			
			'goodsMessage' 	=> $post['goodsMessage'],// 商品信息
			
			'status'		=> 1
		];

		$where  = ['id' => $post['id']];
		$update = $this->procurement_model->update($data, $where);		
		if (!$update) {
			echo '数据错误, 请重新提交';
			exit;
		} else {
			// 添加审核管理里面
				// 根据总金额判断审核层级	
			$amount = $post['amount'];
			if ($amount > 0) {
					if ($amount > 0 && $amount <= 100000) {
						$num = 3;
					} else if ($amount > 100000 && $amount <= 500000) {
						$num = 4;
					} else if ($amount > 500000) {
						$num = 5;
					}	
				} else {
					echo '金额必须有效';
					exit;
				}
			switch ($post['type']) {				
						case '普通需求单':
					$type = 1;
					break;
				
				case '招投标项目需求单':
					$type = 2;
					break;
				
				case '采购项目单':
					$type = 3;
					break;
					
				case '采购退货单':
					$type = 5;
					break;
				
				case '采购换货单':
					$type = 6;
					break;
									
				default:
					$type = 10;
					break;
			}
			$checkData = [
				'type' 			=> $type,
				'relevanceId' 	=> $post['id'], //返回主键id
				'checkinfo' 	=> '',
				'checker' 		=> $post['manager'],
				'status' 		=> 0,
				'checkStatus' 	=> 0,
				'howLevelCheck' => $num,
				'createTime' 	=> time(),
				'checkOrderType'=> $post['type'],
			];
			$res = $this->check_model->add($checkData);
		}

		if ($res) {
			echo '提交成功';
		} else {
			echo '数据错误, 请查看, 并重新提交';
		}
	}

	// 删除功能
	public function remove() 
	{
		$id = $this->input->get('id');
		$this->procurement_model->remove(array('id' => $id));

		// 为空是项目单,为假的需求单
		if (isset($_GET['type'])) {
			redirect('/admin/procurement/proProject?page=1');
		} else {
			redirect('/admin/procurement/index?page=1');
		}
	}
	
	// 点击项目单编号查看详情
	private function detail() 
	{
		$this->load->view('/admin/procurement/detail');
	}

	// 采购需求单作废功能
	public function invalid() 
	{
		$result = $this->procurement_model->edit(array('status' => 3), array('id' => $this->input->get('id')));

		// 为空是项目单,为假的需求单
		if ($result) {
			redirect('/admin/procurement/index?page=1');
		}
	}
	
// 采购项目单---------------------------------------------------------
	// 采购项目单列表页
	public function proProject() 
	{
		$page_num = $this->config->item('fenye')['pageNum'];
		$start_position = 0;
		$page = ($this->input->get('page')); 
		if ($page) {
			$start_position = ($page - 1) * $page_num;
		}

		// 判断搜索内容是否存在存在就继续
		$data = $this->procurement_model->page('procurement', array('type' => '采购项目单'), $page_num, $start_position); 

		if ($data[0]) {
			$viewData = [
				'list' 	   => $data[0],			  // 这里得到从数据库中的当页数据
				'totalNum' => $data['total_num'], // 这里得到从数据库中的总页数
				'pageNum'  => $page_num, 		  // 每页显示多少条
			];
		} else {
			$viewData = [
				'list' 	   => '', 				  // 这里得到从数据库中的当页数据
				'totalNum' => $data['total_num'], // 这里得到从数据库中的总页数
				'pageNum'  => $page_num, 		  // 每页显示多少条
			];
		}	
		$this->load->view('admin/procurement/project/list', $viewData);
	}

	// 采购项目单作废功能
	public function ProjectInvalid() 
	{
		$result = $this->procurement_model->edit(array('status' => 3), array('id' => $this->input->get('id')));

		// 为空是项目单,为假的需求单
		if ($result) {
			redirect('/admin/procurement/proProject?page=1');
		}
	}

	// 采购项目单新增页面
	public function proProjectAddView() 
	{
		// 获取所属项目数据
		$data['project'] = $this->project_model->getData('id,name', 1);
		$this->load->view('/admin/procurement/project/add', $data);		
	}

	// 采购项目单编辑数据
	public function proProjectEditView() 
	{
		// 读取用户名根据get id		
		$data['list'] = $this->procurement_model->getByFieldQueryData('*', array('id' => $this->input->get('id')), 0);

		// 如果不存在直接跳转到404页面
		if (!$data['list']) {
			redirect('/home/error');
		}

		if ($data['list']['goodsMessage']) {
			$data['list']['goodsMessage'] = json_decode($data['list']['goodsMessage'], true);

			foreach ($data['list']['goodsMessage'] as $k => $v) {
				if (isset($v['dataId'])) {
					$arg = [
						'product_id' => $v['dataId'],
					];
				}

				$isStock = $this->goodsStockPrice_model->getByFieldQueryData($fields = '*', $arg, $isMore = 0);
			}

			foreach ($data['list']['goodsMessage'] as $k2 => $v2) {
				if ($isStock) {
					if (!empty($v2['order'])) {
						$data['list']['goodsMessage'][$k2]['isStock'] = 1;

					} else {
						$data['list']['goodsMessage'][$k2]['isStock'] = 0;
					}
				}
			}
		}

		$data['project'] = $this->project_model->getData('id,name', 1);
		$this->load->view('/admin/procurement/project/edit', $data);
	}

// 采购进货单---------------------------------------------------------
	// 进货单列表页面
	public function purchaseOrder() 
	{
		$page_num = $this->config->item('fenye')['pageNum']; 
		$start_position = 0; 
		$page = ($this->input->get('page')); 
		if ($page) {
			$start_position = ($page - 1) * $page_num;
		}

		$status = (isset($_GET['status'])) ? trim($_GET['status']) : 123;
		$data = $this->purchaseOrder_model->page('purchaseOrder', 0, $page_num, $start_position); 

		if ($data) {
			$viewData = [
				'list'		=> $data[0], 
				'totalNum'  => $data['total_num'], 
				'pageNum'   => $page_num, 
				'supplier'  => $this->supplier_model->getData('id, name', 1),
			];
		} else {
			$viewData = [
				'list' 		=> $data[0], 			//这里得到从数据库中的当页数据
				'totalNum'  => $data['total_num'],  //这里得到从数据库中的总页数
				'pageNum' 	=> $page_num, 			//每页显示多少条
				'supplier' 	=> $this->supplier_model->getData('id,name', 1),
			];
		}
		$this->load->view('admin/procurement/purchaseOrder/list', $viewData);
	}

	// 进货单新增页面
	public function purchaseOrderAddView() 
	{
		// 添加项目列表
		$data['project'] = $this->project_model->getData('id,name', 1);
		$data['supplier'] = $this->supplier_model->getData('id,name', 1);

		$this->load->view('/admin/procurement/purchaseOrder/add', $data);
	}

	// 进货单新增功能
	public function purchaseOrderAdd() 
	{
		$post = $this->input->post();
		// 合同信息
		$contractInfo = [
			'amountSmall' 		=> trim($post['amountSmall']),
			'deliveryType' 		=> trim($post['deliveryType']),
			'freight' 			=> trim($post['freight']),
			'jiaohuoTime' 		=> trim($post['jiaohuoTime']),
			'payWay' 			=> trim($post['payWay']),
			'address' 			=> trim($post['address']),
			'amountBig' 		=> trim($post['amountBig']),
			'deliveryAddress' 	=> trim($post['deliveryAddress']),
			'logistics' 		=> trim($post['logistics']),
			'paymentWay' 		=> trim($post['paymentWay']),
			'invoice' 			=> trim($post['invoice']),
		];
		
		// 报价确认单的地址
		if ($_FILES['confirm']['error'] == 0) {
			$mime4 = substr($_FILES['confirm']['name'], strrpos($_FILES['confirm']['name'], '.')); // 取得上传图片的后缀名

			$confirmName = 'purchaseOrder/' . date('YmdHis') . rand(1000, 2000) . $mime4;
			$this->qiniu->upload($_FILES['confirm']['tmp_name'], $confirmName);
			$ConfirmCard = $this->config->item('qiniu')['url'] . $confirmName;
			
		} else {
			$ConfirmCard = '';
		}

		// 支付信息
		$payInfo = $this->input->post('payInfo');

		__logInfo('payInfo', $payInfo[0]['prepay']);

		// 基本信息
		$data = [
			'name' 	=> trim($this->input->post('name')),
			'source' => trim($this->input->post('source')),
			'type' => trim($this->input->post('type')),
			'purchaseCode' => trim($this->input->post('purchaseCode')),
			'content' => trim($this->input->post('content')),
			'needCode' => trim($this->input->post('needCode')),
			'supplier' => trim($this->input->post('supplier')),
			'createMan' => trim($this->input->post('createMan')),
			'documentTime' => strtotime($this->input->post('documentTime')),
			'expectEndTime' => strtotime($this->input->post('expectEndTime')), //基本信息
			'confirmCard' => $ConfirmCard, //报价确认单
			'gid' => json_encode($this->input->post('goods')), //商品信息
			'payInfo' => json_encode($payInfo, JSON_UNESCAPED_UNICODE), //付款信息
			'contractInfo' => json_encode($contractInfo, JSON_UNESCAPED_UNICODE), //合同信息
			'createTime' => time(),
			'goodsMessage' => $this->input->post('goodsMessage'),
			'attribute' => $this->input->post('attribute'),
			'amount' => $this->input->post('amount'),
		];

		if ($this->input->post('action') == '暂存') {
			// 状态为0 待提交
			$data['status'] = 0;
			$data['onStatus'] = 0;
		} else {
			// 状态为1 审核中
			$data['status'] = 1;
			$data['onStatus'] = 1;
		}
		
		$resultData = $this->purchaseOrder_model->addId($data);

		// 当状态为提交的时候添加审核管理里面
		if ($data['status'] = 1) {
			// 如果需求单存在的话，更新需求单状态
			if (isset($_GET['needCode']) && $_GET['needCode']) {
				// 已完成的状态
				$proStatus = [
					'status' => 5,
				];
				$proWhere = [
					'needCode' => $_GET['needCode'],
				];

				$this->procurement_model->edit($proStatus, $proWhere);
			}
			// 如果标书文件存在的话，更新标书文件的状态
			if (isset($_POST['confirmId']) && $_POST['confirmId']) {
				// 已进货的状态
				$confirmStatus = [
					'status' => 3,
				];
				$confirmWhere = [
					'id' => $_POST['confirmId'],
				];

				__logInfo('d', $_POST['confirmId']);

				$this->biddingconfirm_model->edit($confirmStatus, $confirmWhere);
			}

			$checkData = [
				'type' 			 => 4,
				'relevanceId' 	 => $resultData, //返回主键id
				'checkinfo'		 => '',
				'checker' 		 => trim($this->input->post('payMan')),
				'status' 		 => 0,
				'checkStatus' 	 => 0,
				'howLevelCheck'  => '',
				'createTime' 	 => time(),
				'checkOrderType' => '采购进货单'
			];
			$this->check_model->add($checkData);
		}

		if ($resultData) {
			redirect('/admin/procurement/purchaseOrder?page=1&needCode=' . $data['needCode'] . '');
		}
	}

	// 进货单编辑功能
	public function purchaseOrderEdit() 
	{
		// 状态0和1的基础信息编辑
		$where = [
			'id' => $this->input->post('id'),
		];

		$goodsMessage = $this->input->post('goodsMessage');
		// 支付信息
		$payInfo = $this->input->post('payInfo');

		__logInfo('payInfoEdit', $payInfo[0]['prepay']);

		switch ($this->input->post('actionStatus')) {
		case 0:
			// 合同信息
			$contractInfo = [
				'amountSmall' => trim($this->input->post('amountSmall')),
				'deliveryType' => trim($this->input->post('deliveryType')),
				'freight' => trim($this->input->post('freight')),
				'jiaohuoTime' => trim($this->input->post('jiaohuoTime')),
				'payWay' => trim($this->input->post('payWay')),
				'address' => trim($this->input->post('address')),
				'amountBig' => trim($this->input->post('amountBig')),
				'deliveryAddress' => trim($this->input->post('deliveryAddress')),
				'logistics' => trim($this->input->post('logistics')),
				'paymentWay' => trim($this->input->post('paymentWay')),
				'invoice' => trim($this->input->post('invoice')),
			];

			// 报价确认单的地址
			if ($_FILES['confirm']['error'] == 0) {
				$mime4 = substr($_FILES['confirm']['name'], strrpos($_FILES['confirm']['name'], '.')); // 取得上传图片的后缀名

				$confirmName = 'purchaseOrder/' . date('YmdHis') . rand(1000, 2000) . $mime4;
				$this->qiniu->upload($_FILES['confirm']['tmp_name'], $confirmName);

				$ConfirmCard = $this->config->item('qiniu')['url'] . $confirmName;

			} else {
				$ConfirmCard = $this->input->post('confirmImg');

			}

			// 基本信息
			$data = [
				'name' => trim($this->input->post('name')),
				'source' => trim($this->input->post('source')),
				'type' => trim($this->input->post('type')),
				'purchaseCode' => trim($this->input->post('purchaseCode')), //进货单编号
				'content' => trim($this->input->post('content')),
				'needCode' => trim($this->input->post('needCode')),
				'supplier' => trim($this->input->post('supplier')),
				'createMan' => trim($this->input->post('createMan')),
				'documentTime' => strtotime($this->input->post('documentTime')),
				'expectEndTime' => strtotime($this->input->post('expectEndTime')), //基本信息
				'confirmCard' => $ConfirmCard, //报价确认单
				'gid' => json_encode($this->input->post('goods')), //商品信息
				'payInfo' => json_encode($payInfo, JSON_UNESCAPED_UNICODE), //付款信息
				'contractInfo' => json_encode($contractInfo, JSON_UNESCAPED_UNICODE), //合同信息
				'createTime' => time(),
				'goodsMessage' => $goodsMessage,
				'attribute' => $this->input->post('attribute'),
				'amount' => $this->input->post('amount'),
				'status' => 1,
				'onStatus' => 1,
			];
			break;
		case 2:
			// 出厂抽检报告单
			if ($_FILES['reportCard']['error'] == 0) {
				$mime = substr($_FILES['reportCard']['name'], strrpos($_FILES['reportCard']['name'], '.')); // 取得上传图片的后缀名

				$reportCardName = 'purchaseOrder/' . date('YmdHis') . rand(1000, 2000) . $mime;
				$this->qiniu->upload($_FILES['reportCard']['tmp_name'], $reportCardName);

				$data['reportCard'] = $this->config->item('qiniu')['url'] . $reportCardName;
				$data['status'] = $this->input->post('onStatus');
				$data['onStatus'] = $this->input->post('status');
				$data['payInfo'] = json_encode($payInfo, JSON_UNESCAPED_UNICODE); //付款信息
			}
			break;
			
		case 3:
			// 物流信息
			$logistics = [
				'courierNumber' => trim($this->input->post('courierNumber')), //快递单号
				'express' => trim($this->input->post('express')), //物流公司
			];

			if ($_FILES['expressCard']['error'] == 0) {
				$mime = substr($_FILES['expressCard']['name'], strrpos($_FILES['expressCard']['name'], '.')); // 取得上传图片的后缀名

				$expressCardName = 'purchaseOrder/' . date('YmdHis') . rand(1000, 2000) . $mime;
				$this->qiniu->upload($_FILES['expressCard']['tmp_name'], $expressCardName);

				$logistics['expressCard'] = $this->config->item('qiniu')['url'] . $expressCardName;
			}

			if ($_FILES['terminalCard']['error'] == 0) {
				$mime2 = substr($_FILES['terminalCard']['name'], strrpos($_FILES['terminalCard']['name'], '.')); // 取得上传图片的后缀名

				$terminalCardName = 'purchaseOrder/' . date('YmdHis') . rand(1000, 2000) . $mime2;
				$this->qiniu->upload($_FILES['terminalCard']['tmp_name'], $terminalCardName);
				$logistics['terminalCard'] = $this->config->item('qiniu')['url'] . $terminalCardName;
			}

			$data['logisticsInfo'] = json_encode($logistics, JSON_UNESCAPED_UNICODE);
			$data['status'] 	   = $this->input->post('onStatus');
			$data['onStatus']	   = $this->input->post('status');
			$data['payInfo'] 	   = json_encode($payInfo, JSON_UNESCAPED_UNICODE); // 付款信息

			$stockPut = [
				'type' => '采购需求单',
				'stockPutCode' => 'RK' . date('Ymd') . rand(100, 999),
				'purchaseCode' => trim($this->input->post('purchaseCode')), // 进货单编号
				'createMan' => $_COOKIE['nickname'],
				'supplier' => $this->input->post('supplier'),
				'payInfo' => json_encode($payInfo, JSON_UNESCAPED_UNICODE), // 付款信息,
				'logisticsInfo' => json_encode($logistics, JSON_UNESCAPED_UNICODE),
				'content' => $this->input->post('content'),
				'status' => 0,
				'createTime' => time(),
				'attribute' => $this->input->post('attribute'),
				'goodsMessage' => $goodsMessage,
				'source' => $data['source'] // 进入单所属项目
			];

			$this->stockPut_model->add($stockPut);

			break;
		case 4:
			// 质押金付款单

			if ($_FILES['pledgeGoldCard']['error'] == 0) {
				$mime = substr($_FILES['pledgeGoldCard']['name'], strrpos($_FILES['pledgeGoldCard']['name'], '.')); //取得上传图片的后缀名

				$pledgeGoldCardName = 'purchaseOrder/' . date('YmdHis') . rand(1000, 2000) . $mime;
				$this->qiniu->upload($_FILES['pledgeGoldCard']['tmp_name'], $pledgeGoldCardName);

				$data['pledgeGoldCard'] = $this->config->item('qiniu')['url'] . $pledgeGoldCardName;
			}

			$data['status']   = $this->input->post('onStatus');
			$data['onStatus'] = $this->input->post('status');
			$data['payInfo']  = json_encode($payInfo, JSON_UNESCAPED_UNICODE); //付款信息

			// 第五步完成的时候，插入endTime
			$data['endTime'] = time();
			__logInfo('第四步endTime', $data['endTime']);

			break;
		case 5:

			$data['status'] = $this->input->post('onStatus');
			$data['onStatus'] = $this->input->post('status');
			$data['payInfo'] = json_encode($payInfo, JSON_UNESCAPED_UNICODE); //付款信息

			break;
		}

		// 是否会有添加失败的情况?
		$resultData = $this->purchaseOrder_model->edit($data, $where);

		// 进货单编辑每次审核的人员
		$count 		 = count(json_decode($payInfo, true));
		$payInfoCode = json_decode($payInfo, true); //格式化后的审核人员

		$checkData   = [
			'checker' => $payInfoCode[$count - 1]['payMan'],
		];
		$this->check_model->edit($checkData, $where);

		if ($resultData) {
			$result = [
				'success' => 1,
			];
		} else {
			$result = [
				'error' => 0000,
			];
		}

		echo json_encode($result);
	}

	// 进货单编辑页面
	public function purchaseEditView() {

		// 读取用户名根据get id
		$data['list'] = $this->purchaseOrder_model->getByFieldQueryData('*', array('id' => $this->input->get('id')), 0);

		// 如果不存在直接跳转到404页面
		if (!$data['list']) {
			redirect('/home/error');
		}

		$data['list']['contractInfo'] = json_decode($data['list']['contractInfo'], true);
		$data['list']['payInfo'] = json_decode($data['list']['payInfo'], true);
		$data['list']['logisticsInfo'] = json_decode($data['list']['logisticsInfo'], true);
		$data['list']['goodsMessage'] = json_decode($data['list']['goodsMessage'], true);

		foreach ($data['list']['goodsMessage'] as $k => $v) {
			if (isset($v['dataId'])) {
				$arg = [
					'product_id' => $v['dataId'],
				];
			} else {
				$data['list']['goodsMessage'][$k]['dataId'] = '';
			}

			$isStock = $this->goodsStockPrice_model->getByFieldQueryData($fields = '*', $arg, $isMore = 0);
		}

		foreach ($data['list']['goodsMessage'] as $k2 => $v2) {
			if (isset($isStock)) {
				if (!empty($v2['order'])) {
					$data['list']['goodsMessage'][$k2]['isStock'] = 1;

				} else {
					$data['list']['goodsMessage'][$k2]['isStock'] = 0;
				}

			} else {
				$data['list']['goodsMessage'][$k2]['isStock'] = 0;
			}
		}

		foreach ($data['list']['payInfo'] as $k => $v) {
			switch ($v['prepay']) {
			case 0.05:
				$data['list']['payInfo'][$k]['prepay'] = '预付款5%';
				break;
			case 0.10:
				$data['list']['payInfo'][$k]['prepay'] = '预付款10%';
				break;
			case 0.15:
				$data['list']['payInfo'][$k]['prepay'] = '预付款15%';
				break;
			case 0.2:
				$data['list']['payInfo'][$k]['prepay'] = '预付款20%';
				break;
			case 0.3:
				$data['list']['payInfo'][$k]['prepay'] = '预付款30%';
				break;
			case 0.4:
				$data['list']['payInfo'][$k]['prepay'] = '预付款40%';
				break;
			case 0.5:
				$data['list']['payInfo'][$k]['prepay'] = '预付款50%';
				break;
			case 0.6:
				$data['list']['payInfo'][$k]['prepay'] = '预付款60%';
				break;
			case 0.7:
				$data['list']['payInfo'][$k]['prepay'] = '预付款70%';
				break;
			case 0.8:
				$data['list']['payInfo'][$k]['prepay'] = '预付款80%';
				break;
			case 1:
				$data['list']['payInfo'][$k]['prepay'] = '预付款100%';
				break;
			}
		}

		$data['project'] = $this->project_model->getData('id,name', 1);
		$data['supplier'] = $this->supplier_model->getData('id,name', 1);

		$this->load->view('/admin/procurement/purchaseOrder/edit', $data);
	}

	// 进货单删除功能
	public function purchaseRemove() {
		$result = $this->purchaseOrder_model->remove(array('id' => $this->input->get('id')));

		if ($result) {
			redirect('/admin/procurement/purchaseOrder?page=1');
		} else {
			echo __alert('参数错误!');
		}
	}

	// 进货单详情页面
	public function purchaseDetail() {
		// 读取id查询数据
		$data['list'] = $this->purchaseOrder_model->getByFieldQueryData('*', array('id' => $this->input->get('id')), 0);

		if (!$data) {
			redirect('/home/error');
		}

		$data['list']['contractInfo'] = json_decode($data['list']['contractInfo'], true);
		$data['list']['payInfo'] = json_decode($data['list']['payInfo'], true);
		$data['list']['logisticsInfo'] = json_decode($data['list']['logisticsInfo'], true);
		$data['list']['goodsMessage'] = json_decode($data['list']['goodsMessage'], true);
		foreach ($data['list']['goodsMessage'] as $k => $v) {
			if (isset($v['dataId'])) {
				$arg = [
					'product_id' => $v['dataId'],
				];
			} else {
				$data['list']['goodsMessage'][$k]['dataId'] = '';
			}

			$isStock = $this->goodsStockPrice_model->getByFieldQueryData($fields = '*', $arg, $isMore = 0);
		}

		foreach ($data['list']['goodsMessage'] as $k2 => $v2) {
			if (isset($isStock)) {
				if (!empty($v2['order'])) {
					$data['list']['goodsMessage'][$k2]['isStock'] = 1;

				} else {
					$data['list']['goodsMessage'][$k2]['isStock'] = 0;
				}

			} else {
				$data['list']['goodsMessage'][$k2]['isStock'] = 0;
			}
		}

		foreach ($data['list']['payInfo'] as $k => $v) {
			switch ($v['prepay']) {
			case 0.05:
				$data['list']['payInfo'][$k]['prepay'] = '预付款5%';
				break;
			case 0.10:
				$data['list']['payInfo'][$k]['prepay'] = '预付款10%';
				break;
			case 0.15:
				$data['list']['payInfo'][$k]['prepay'] = '预付款15%';
				break;
			case 0.2:
				$data['list']['payInfo'][$k]['prepay'] = '预付款20%';
				break;
			case 0.3:
				$data['list']['payInfo'][$k]['prepay'] = '预付款30%';
				break;
			case 0.4:
				$data['list']['payInfo'][$k]['prepay'] = '预付款40%';
				break;
			case 0.5:
				$data['list']['payInfo'][$k]['prepay'] = '预付款50%';
				break;
			case 0.6:
				$data['list']['payInfo'][$k]['prepay'] = '预付款60%';
				break;
			case 0.7:
				$data['list']['payInfo'][$k]['prepay'] = '预付款70%';
				break;
			case 0.8:
				$data['list']['payInfo'][$k]['prepay'] = '预付款80%';
				break;
			case 1:
				$data['list']['payInfo'][$k]['prepay'] = '预付款100%';
				break;
			}

		}

		$data['project'] = $this->project_model->getData('id,name', 1);
		$data['supplier'] = $this->supplier_model->getData('id,name', 1);

		switch ($_GET['status']) {
		case 1:
			$this->load->view('/admin/procurement/purchaseOrder/detail1', $data);
			break;
		case 2:
			$this->load->view('/admin/procurement/purchaseOrder/detail2', $data);
			break;
		case 3:
			$this->load->view('/admin/procurement/purchaseOrder/detail3', $data);
			break;
		case 4:
			$this->load->view('/admin/procurement/purchaseOrder/detail4', $data);
			break;
		case 5:
			$this->load->view('/admin/procurement/purchaseOrder/detail5', $data);
			break;
		}
	}

	// 进货单编辑的时候显示付款信息接口
	public function editCCList() {

		$arg = [
			'id' => $_POST['id'],
		];

		$a = $this->purchaseOrder_model->getByFieldQueryData('payInfo', $arg, 0);

		$b = json_decode($a['payInfo'], true);

		echo json_encode($b[0], JSON_UNESCAPED_UNICODE);
	}
	
	
// 采购退货单---------------------------------------------------------	
	// 退货单列表页面
	public function returnOrder()
	{
		$page_num = $this->config->item('fenye')['pageNum']; //每页的数据
        $start_position = 0; //初始数据
        $page = ($this->input->get('page')); //获取页码数量
        if ($page) {
            $start_position = ($page - 1) * $page_num;
        }

        $status = (isset($_GET['status'])) ? trim($_GET['status']) : 123;

        //判断搜索内容是否存在存在就继续
        $data = $this->returnOrder_model->page('returnOrder', array('type' => '采购退货单'), $page_num, $start_position); // limit查询的数据

        foreach ($data[0] as $k => $v) {
            if (!$v['isEnd'] && $v['status'] == 2) {
                // 退货和换货都叫出库单
                $stockPut = [
                    'type' => $v['type'],
                    'stockOutCode' => 'CK' . date('Ymd') . rand(100, 999),
                    'returnCode' => $v['code'], //关联退货单编号
                    'createMan' => $_COOKIE['nickname'],
                    'supplier' => $v['supplier'],
                    'content' => $v['content'],
                    'status' => 0,
                    'createTime' => time(),
                    'attribute' => $v['attribute'],
                    'goodsMessage' => $v['goodsMessage'],
                    'relevanceId' => $v['id'], //id添加使之关联

                    'source'=> $v['source'], //进入单所属项目

                ];

                $this->stockOut_model->add($stockPut);

                $data2 = [
                    'isEnd' => 1
                ];
                $arg2 = [
                    'id' => $v['id']
                ];
                $this->returnOrder_model->edit($data2, $arg2);
            }
        }

        if ($data) {
            $viewData = [
                'list'	   => $data[0],  		  // 这里得到从数据库中的当页数据
                'totalNum' => $data['total_num'], // 这里得到从数据库中的总页数
                'pageNum'  => $page_num 		  // 每页显示多少条
            ];
        } else {
            $viewData = [
                'list'     => $data[0],  
                'totalNum' => $data['total_num'], 
                'pageNum'  => $page_num

            ];
        }
        $this->load->view('/admin/procurement/returnOrder/list', $viewData);
	}

	// 退货单新增页面
	public function returnOrderAddView() {
		// 添加项目列表
		$data['project'] = $this->project_model->getData('id,name', 1);
		// 添加供应商列表
		$data['supplier'] = $this->supplier_model->getData('id,name', 1);

		$this->load->view('/admin/procurement/returnOrder/add', $data);
	}

	// 新增退货单提交处理
	public function returnOrderAdd() {
		$post = $this->input->post();

		// 基本信息
		$data = [
			'code' 		 	=> trim($post['code']), 			// 编号
			'source' 	 	=> $post['source'], 				// 所属项目
			'createTime' 	=> strtotime($post['createTime']),  // 单据时间
			'content' 	 	=> trim($post['content']), 			// 退货原因

			'name' 			=> trim($post['name']), 			  // 退货单名称
			'supplier' 		=> $post['supplier'], 				  // 供应商
			'endTime' 		=> trim(strtotime($post['endTime'])), // 期望到货时间
			'type' 			=> $post['type'], 					  //类型
			'goodsMessage'  => $post['goodsMessage'], 			  // 商品详细信息
			
			'attribute' 	=> $post['attribute'], 	//种类/数量
			'amount' 		=> $post['amount'], 	//退货金额
					
			// 审批人
			'manager'   	=> $post['manager'],	// 一级审批人, 部门主管
			'safeguard' 	=> $post['safeguard'],	// 二级审批人, 保障中心总监
			'deputy' 		=> $post['deputy'],		// 三级审批人, 分管副总
			'fdeputy' 		=> $post['fdeputy'], 	// 四级审批人, 财务分管副总
			'chairman' 		=> $post['chairman']	// 五级审批人, 董事长 
			];
			
		if ($post['action'] == '提交') {
			// 状态为1 审核中
			$data['status'] = 1;
		} else {
			// 状态为0 待提交
			$data['status'] = 0;
		}
		
		$insertId = $this->returnOrder_model->addId($data);
		if (!$insertId) {
			echo '数据错误, 请重新提交';
			exit;
		}
		// 若插入成功, 且点击的是提交按钮, 则开始进行审核
		if ($data['status'] == 1) {				
			// 添加审核管理里面
				// 根据总金额判断审核层级	
			$amount = $post['amount'];
			if ($amount > 0) {
					if ($amount > 0 && $amount <= 100000) {
						$num = 3;
					} else if ($amount > 100000 && $amount <= 500000) {
						$num = 4;
					} else if ($amount > 500000) {
						$num = 5;
					}	
				} else {
					echo '金额必须有效';
					exit;
				}
			switch ($post['type']) {				
				case '采购退货单':
					$type = 5;
					break;
				
				case '采购换货单':
					$type = 6;
					break;
									
				default:
					$type = 10;
					break;
			}
			$checkData = [
				'type' 			=> $type,
				'relevanceId' 	=> $insertId, //返回主键id
				'checkinfo' 	=> '',
				'checker' 		=> $post['manager'],
				'status' 		=> 0,
				'checkStatus' 	=> 0,
				'howLevelCheck' => $num,
				'createTime' 	=> time(),
				'checkOrderType'=> $post['type'],
			];
			$res = $this->check_model->add($checkData);
		} else {
			echo '暂存成功';
			exit;
		}
		if ($res) {
			echo '提交成功';
		} else {
			echo '数据错误, 请查看, 并重新提交';
		}
		
	}

	// 退货单编辑页面
    public function returnOrderEditView()
    {
        // 读取用户名根据get id
        $arg = [
            'id' => $this->input->get('id')
        ];
		
        $data['list'] = $this->returnOrder_model->getByFieldQueryData('*', $arg, 0);

        //如果不存在直接跳转到404页面
        if (!$data['list']) {
            redirect('/home/error');
        }
		
        $data['list']['goodsMessage'] = json_decode($data['list']['goodsMessage'], true);

        //todo 是否要做跳转页面
        if ($data['list']['goodsMessage']) {
            foreach ($data['list']['goodsMessage'] as $k => $v) {
                if (isset($v['dataId'])) {
                    $arg = [
                        'product_id' => $v['dataId']
                    ];
                } else {
                    $data['list']['goodsMessage'][$k]['dataId'] = '';
                }

                $isStock = $this->goodsStockPrice_model->getByFieldQueryData($fields = '*', $arg, $isMore = 0);
            }

            foreach ($data['list']['goodsMessage'] as $k2 => $v2) {
                if (isset($isStock)) {
                    if (!empty($v2['order'])) {
                        $data['list']['goodsMessage'][$k2]['isStock'] = 1;
                    } else {
                        $data['list']['goodsMessage'][$k2]['isStock'] = 0;
                    }
                } else {
                    $data['list']['goodsMessage'][$k2]['isStock'] = 0;
                }
            }
        }
		if ($data['list']['endTime'] === '0') {
			$data['list']['endTime'] = '请选择时间';
		} else {
			$data['list']['endTime'] = date('Y-m-d', $data['list']['endTime']);
		}
		
        $data['project']  = $this->project_model->getData('id,name', 1);
        $data['supplier'] = $this->supplier_model->getData('id,name', 1);
        $this->load->view('/admin/procurement/returnOrder/edit', $data);
    }

	// 退货单编辑功能 与 换货单新增使用同一功能
	public function returnOrderEdit() {
		$post = $this->input->post();

		$arr = empty($post);
		if ($arr) {
			echo '请填入数据';
			exit;
		}

		// 基本信息
		$data = [ 
			// 编码不用改
			'source' 	 	=> $post['source'], // 所属项目
			'createTime' 	=> strtotime($post['createTime']), // 单据时间
			'content' 	 	=> trim($post['content']), // 退货原因

			'name' 			=> trim($post['name']), // 退货单名称
			'supplier' 		=> $post['supplier'], // 供应商
			'endTime' 		=> strtotime($post['endTime']), // 期望到货时间
			'goodsMessage'  => $post['goodsMessage'], // 商品详细信息

			'type' 			=> trim($post['type']), // 类型
			'attribute' 	=> trim($post['attribute']), // 种类/数量
			'amount' 		=> trim($post['amount']), // 退货金额
			
			// 审批人
			'manager'   	=> $post['manager'],	// 一级审批人, 部门主管
			'safeguard' 	=> $post['safeguard'],	// 二级审批人, 保障中心总监
			'deputy' 		=> $post['deputy'],		// 三级审批人, 分管副总
			'fdeputy' 		=> $post['fdeputy'], 	// 四级审批人, 财务分管副总
			'chairman' 		=> $post['chairman'],	// 五级审批人, 董事长 
			
			'status'		=> 1	// 不能再编辑
			];
			
		$where = ['id' => $post['id']];
		$update = $this->returnOrder_model->update($data, $where);

		if (!$update) {
			echo '数据错误, 请重新提交';
			exit;
		} else {
			// 添加审核管理里面
				// 根据总金额判断审核层级	
			$amount = $post['amount'];
			if ($amount > 0) {
					if ($amount > 0 && $amount <= 100000) {
						$num = 3;
					} else if ($amount > 100000 && $amount <= 500000) {
						$num = 4;
					} else if ($amount > 500000) {
						$num = 5;
					}	
				} else {
					echo '金额必须有效';
					exit;
				}
			switch ($post['type']) {				
				case '采购退货单':
					$type = 5;
					break;
				
				case '采购换货单':
					$type = 6;
					break;
									
				default:
					$type = 10;
					break;
			}
			$checkData = [
				'type' 			=> $type,
				'relevanceId' 	=> $post['id'], //返回主键id
				'checkinfo' 	=> '',
				'checker' 		=> $post['manager'],
				'status' 		=> 0,
				'checkStatus' 	=> 0,
				'howLevelCheck' => $num,
				'createTime' 	=> time(),
				'checkOrderType'=> $post['type'],
			];
			$res = $this->check_model->add($checkData);
		}

		if ($res) {
			echo '提交成功';
		} else {
			echo '数据错误, 请查看, 并重新提交';
		}
	}

	// 退换单删除功能,并删除商品出库的数据
	public function returnRemove() {

		$this->returnOrder_model->trans_begin();
		try {
			$where = [
				'id' => $_GET['id'],
			];
			
			if (!$_GET['id']) {
				die(__alert('id不存在非法删除！'));
			}

			// 如果都为真，再去查询关联的code
			$code = $this->returnOrder_model->getByFieldQueryData('id,code', array('id' => $this->input->get()), 0);
			
			__logInfo('code', $code['code']);
			// 如果code存在，就一起删除，否则就删除退换货单。
			if ($code['code']) {
				$outWhere = [
					'returnCode' => $code['code'],
				];
				// 退换单删除的时候同时删除商品出库的对应数据
				// 通过id，查询对应的id  code。
				$outRemove = $this->stockOut_model->remove($outWhere);
				$remove = $this->returnOrder_model->remove($where);

				if ($outRemove) {
					//到这里为真全部提交
					$this->returnOrder_model->trans_commit();
					$this->stockOut_model->trans_commit();

					if (isset($_GET['type'])) {
						redirect('/admin/procurement/returnOrder?page=1');
					} else {
						redirect('/admin/procurement/barterOrder?page=1');
					}

				}
			} else {
				$remove = $this->returnOrder_model->remove($where);

				if ($remove) {
					// 如果没有关联商品出库表没有关联cdoe，则说明没有关联，也提交
					$this->returnOrder_model->trans_commit();

					if (isset($_GET['type'])) {
						redirect('/admin/procurement/returnOrder?page=1');
					} else {
						redirect('/admin/procurement/barterOrder?page=1');
					}
				} else {
					throw new Exception("删除失败，id不存在");
				}

			}

		} catch (Exception $e) {
			// 如果出错，全部回滚
			__logInfo('删除采购退换货单失败的原因：', $e->getMessage());
			$this->returnOrder_model->trans_rollback();
		}
	}

	// 退货单作废功能
	public function returnInvalid() 
	{
		// status = 3 作废功能
		$this->returnOrder_model->edit(array('status' => 3), array('id' => $this->input->get('id')));
		
		// 为真是退货单,为假的换货单
		if (isset($_GET['type'])) {
			redirect('/admin/procurement/returnOrder?page=1');
		} else {
			redirect('/admin/procurement/barterOrder?page=1');
		}
	}

// 采购换货单---------------------------------------------------------
	// 换货单列表页面
	public function barterOrder() 
	{
		$page_num = $this->config->item('fenye')['pageNum']; //每页的数据
		$start_position = 0; //初始数据
		$page = ($this->input->get('page')); //获取页码数量
		if ($page) {
			$start_position = ($page - 1) * $page_num;
		}

		$status = (isset($_GET['status'])) ? trim($_GET['status']) : 123;

		// 判断搜索内容是否存在存在就继续
		$data = $this->returnOrder_model->page('returnOrder', array('type' => '采购换货单'), $page_num, $start_position); 
		
		if ($data) {
			$viewData = [
				'list' 	   => $data[0],			  // 这里得到从数据库中的当页数据
				'totalNum' => $data['total_num'], // 这里得到从数据库中的总页数
				'pageNum'  => $page_num		  	  // 每页显示多少条

			];
		} else {
			$viewData = [
				'list' => $data[0], 
				'totalNum' => $data['total_num'], 
				'pageNum' => $page_num
			];
		}
		$this->load->view('/admin/procurement/barterOrder/list', $viewData);
	}

	// 换货单新增页面
	public function barterOrderAddView() 
	{
		// 添加项目列表
		$data['project'] = $this->project_model->getData('id,name', 1);
		// 添加供应商列表
		$data['supplier'] = $this->supplier_model->getData('id,name', 1);

		$this->load->view('/admin/procurement/barterOrder/add', $data);
	}
	
	// 换货单编辑页面
	public function barterOrderEditView() 
	{

		//读取用户名根据get id
		$arg = [
			'id' => $this->input->get('id'),
			'type' => '采购换货单',
		];

		$data['list'] = $this->returnOrder_model->getByFieldQueryData('*', $arg, 0);

		//如果不存在直接跳转到404页面
		if (!$data['list']) {
			redirect('/home/error');
		}

		$data['list']['goodsMessage'] = json_decode($data['list']['goodsMessage'], true);

		foreach ($data['list']['goodsMessage'] as $k => $v) {
			if (isset($v['dataId'])) {
				$arg = [
					'product_id' => $v['dataId'],
				];
			}

			$isStock = $this->goodsStockPrice_model->getByFieldQueryData($fields = '*', $arg, $isMore = 0);

		}

		foreach ($data['list']['goodsMessage'] as $k2 => $v2) {
			if ($isStock) {
				if (!empty($v2['order'])) {
					$data['list']['goodsMessage'][$k2]['isStock'] = 1;

				} else {
					$data['list']['goodsMessage'][$k2]['isStock'] = 0;
				}

			}
		}
		$data['project'] = $this->project_model->getData('id,name', 1);
		$data['supplier'] = $this->supplier_model->getData('id,name', 1);

		$this->load->view('/admin/procurement/barterOrder/edit', $data);
	}

	// 换货单新增功能
	private function barterOrderAdd() {

		//合同信息
		$contractInfo = [
			'amountSmall' => trim($this->input->post('amountSmall')),
			'deliveryType' => trim($this->input->post('deliveryType')),
			'freight' => trim($this->input->post('freight')),
			'jiaohuoTime' => trim($this->input->post('jiaohuoTime')),
			'payWay' => trim($this->input->post('payWay')),
			'address' => trim($this->input->post('address')),
			'amountBig' => trim($this->input->post('amountBig')),
			'deliveryAddress' => trim($this->input->post('deliveryAddress')),
			'logistics' => trim($this->input->post('logistics')),
			'paymentWay' => trim($this->input->post('paymentWay')),
			'invoice' => trim($this->input->post('invoice')),
		];

		// 加载上传库
		$this->load->library('upload', __upload('pur', 'purchase'));
		$upload = 'upload';
		$fileName = 'upload/purchase';

		if (!is_dir($upload)) {
			mkdir($upload);
		} else {
			if (!is_dir($fileName)) {
				mkdir($fileName);
			}
		}

		// 上传文件，这里的pic是视图中file控件的name属性
		if ($this->upload->do_upload('confirm')) {
			$ResultConfirm = $this->upload->data();
			//报价确认单的地址
			$ConfirmCard = '/upload/purchase/' . $ResultConfirm['file_name'];
		} else {
			$error = array('error' => $this->upload->display_errors());

			print_r($error);
		}


		//支付信息
		$payInfo = [
			0 => [
				'prepay' => trim($this->input->post('prepay')),
				'payMan' => trim($this->input->post('payMan')),
			],
		];

		//基本信息
		$data = [
			'name' => trim($this->input->post('name')),
			'source' => trim($this->input->post('source')),
			'type' => trim($this->input->post('type')),
			'purchaseCode' => trim($this->input->post('purchaseCode')),
			'content' => trim($this->input->post('content')),
			'needCode' => trim($this->input->post('needCode')),
			'supplier' => trim($this->input->post('supplier')),
			'createMan' => trim($this->input->post('createMan')),
			'documentTime' => strtotime($this->input->post('documentTime')),
			'expectEndTime' => strtotime($this->input->post('expectEndTime')), //基本信息
			'confirmCard' => $ConfirmCard, //报价确认单
			'gid' => json_encode($this->input->post('goods')), //商品信息
			'payInfo' => json_encode($payInfo, JSON_UNESCAPED_UNICODE), //付款信息
			'contractInfo' => json_encode($contractInfo, JSON_UNESCAPED_UNICODE), //合同信息
			'createTime' => time(),
		];

		if ($this->input->post('action') == '暂存') {
			//状态为0 待提交
			$data['status'] = 0;
			$data['onStatus'] = 0;
		} else {
			//状态为1 审核中
			$data['status'] = 1;
			$data['onStatus'] = 1;
		}

		$resultData = $this->purchaseOrder_model->add($data);

		if ($resultData) {
			redirect('/admin/procurement/barterOrder?page=1');
		}
	}

	// 换货单编辑功能
	private function barterOrderEdit() 
	{
		// 合同信息
		$contractInfo = [
			'amountSmall' => trim($this->input->post('amountSmall')),
			'deliveryType' => trim($this->input->post('deliveryType')),
			'freight' => trim($this->input->post('freight')),
			'jiaohuoTime' => trim($this->input->post('jiaohuoTime')),
			'payWay' => trim($this->input->post('payWay')),
			'address' => trim($this->input->post('address')),
			'amountBig' => trim($this->input->post('amountBig')),
			'deliveryAddress' => trim($this->input->post('deliveryAddress')),
			'logistics' => trim($this->input->post('logistics')),
			'paymentWay' => trim($this->input->post('paymentWay')),
			'invoice' => trim($this->input->post('invoice')),
		];

		// 加载上传库
		$this->load->library('upload', __upload('pur', 'purchase'));
		$upload = 'upload';
		$fileName = 'upload/purchase';
		if (!is_dir($upload)) {
			mkdir($upload);
		} else {
			if (!is_dir($fileName)) {
				mkdir($fileName);
			}
		}
		// 上传文件，这里的pic是视图中file控件的name属性
		if ($this->upload->do_upload('confirm')) {
			$ResultConfirm = $this->upload->data();
			//报价确认单的地址
			$ConfirmCard = '/upload/purchase/' . $ResultConfirm['file_name'];
		} else {
			$ConfirmCard = $this->input->post('confirmImg');
		}

		// 支付信息
		$payInfo = $this->input->post('payInfo');

		// 基本信息
		$data = [
			'name' => trim($this->input->post('name')),
			'source' => trim($this->input->post('source')),
			'type' => trim($this->input->post('type')),
			'purchaseCode' => trim($this->input->post('purchaseCode')), //进货单编号
			'content' => trim($this->input->post('content')),
			'needCode' => trim($this->input->post('needCode')),
			'supplier' => trim($this->input->post('supplier')),
			'createMan' => trim($this->input->post('createMan')),
			'documentTime' => strtotime($this->input->post('documentTime')),
			'expectEndTime' => strtotime($this->input->post('expectEndTime')), //基本信息
			'confirmCard' => $ConfirmCard, //报价确认单
			'gid' => json_encode($this->input->post('goods')), //商品信息
			'payInfo' => json_encode($payInfo, JSON_UNESCAPED_UNICODE), //付款信息
			'contractInfo' => json_encode($contractInfo, JSON_UNESCAPED_UNICODE), //合同信息
			'createTime' => time(),
		];

		switch ($this->input->post('actionStatus')) {
		case 0:
			$data['status'] = 1;
			$data['onStatus'] = 1;
			break;
		case 2:
			// 出厂抽检报告单
			// 加载上传库
			// 上传文件，这里的pic是视图中file控件的name属性
			if ($this->upload->do_upload('reportCard')) {
				$ResultReport = $this->upload->data();
				//出厂抽检报告单
				$data['reportCard'] = '/upload/purchase/' . $ResultReport['file_name'];
				$data['status'] = $this->input->post('onStatus');
				$data['onStatus'] = $this->input->post('status');
			}
			break;
		case 3:
			// 物流信息
			$logistics = [
				'courierNumber' => trim($this->input->post('courierNumber')), //快递单号
				'express' => trim($this->input->post('courierNumber')), //物流公司
			];
			if ($this->upload->do_upload('expressCard')) {
				$ResultExpressCard = $this->upload->data();
				// 报价确认单的地址
				$logistics['expressCard'] = '/upload/purchase/' . $ResultExpressCard['file_name'];

			}
			if ($this->upload->do_upload('terminalCard')) {
				$ResultTerminalCard = $this->upload->data();
				//报价确认单的地址
				$logistics['terminalCard'] = '/upload/purchase/' . $ResultTerminalCard['file_name'];
			}
			$data['logisticsInfo'] = json_encode($logistics, JSON_UNESCAPED_UNICODE);
			$data['status'] = $this->input->post('onStatus');
			$data['onStatus'] = $this->input->post('status');

			// 把数据写入商品入库表
			// tattribute参数
			$stockPut = [
				'type' => '采购需求单',
				'stockPutCode' => 'RK' . date('Y-m-d') . rand(100, 999),
				'purchaseCode' => trim($this->input->post('purchaseCode')), //进货单编号
				'createMan' => $_COOKIE['nickname'],
				'supplier' => $this->input->post('supplier'),
				'gid' => json_encode($this->input->post('goods')),
				'payInfo' => json_encode($payInfo, JSON_UNESCAPED_UNICODE), //付款信息,
				'logisticsInfo' => json_encode($logistics, JSON_UNESCAPED_UNICODE),
				'content' => $this->input->post('content'),
				'status' => 0,
				'createTime' => time(),
				'attribute' => $_POST['attribute'],
			];

			$this->stockPut_model->add($stockPut);

			break;
		case 4:
			// 质押金付款单
			if ($this->upload->do_upload('pledgeGoldCard')) {
				$ResultPledgeGold = $this->upload->data();
				$data['pledgeGoldCard'] = '/upload/purchase/' . $ResultPledgeGold['file_name'];

			}
			$data['status'] = $this->input->post('onStatus');
			$data['onStatus'] = $this->input->post('status');
			break;
		case 5:

			$data['status'] = $this->input->post('onStatus');
			$data['onStatus'] = $this->input->post('status');
			break;
		}

		// 是否会有添加失败的情况?
		$resultData = $this->returnOrder_model->edit($data, array('id' => $this->input->post('id')));

		if ($resultData) {
			echo '<script>alert("修改成功")</script>';
			redirect('/admin/procurement/barterOrder?page=1');
		}
	}
	
// 导出功能---------------------------------------------------------
	public function daochu() 
	{
		$this->load->library('Excels');

		// 表格标题
		$title = [
			0 => [
				0 => '序号',
				1 => '采购编码',
				2 => '采购名字',
				3 => '采购简称',
				4 => '采购联络人',
				5 => '采购联系人',
				6 => '联系号码',
				7 => '地址',
				8 => '创建时间',
				9 => 'size',
				10 => 'nature',
				11 => 'isProducers',
				12 => 'vender',
				13 => 'mail',
				14 => 'note',
			],
		];

		$data = $this->procurement_model->getData('*', 1);

		//表格内容
		//        $content =  [
		//            0 => [
		//                0 => '序号',
		//                1 => '采购编码',
		//                2 => '采购名字',
		//                3 => '采购简称',
		//                4 => '采购联络人',
		//                5 => '采购联系人',
		//                6 => '联系号码',
		//                7 => '地址',
		//                8 => '创建时间',
		//                9 => 'size',
		//                10 => 'nature',
		//                11 => 'isProducers',
		//                12 => 'vender',
		//                13 => 'mail',
		//                14 => 'note',
		//        ],
		//            1 => [
		//                0 => '12312人',
		//                1 => '所发生的丰富的',
		//                2 => '积分高级人机'
		//        ]];

		// 二维数据
		$this->excels->exports($data, $title);

	}

	// todo 批量导出功能?
	public function purchaseDaochu() {
		
	}
	
	// 测试
	private function test() {
		$stockPut = [
			'type' => $_POST['type'],
			'stockOutCode' => 'RK' . date('Ymd') . rand(100, 999),
			'returnCode' => $_POST['code'], //关联退货单编号
			'createMan' => $_COOKIE['nickname'],
			'supplier' => $this->input->post('supplier'),
			'content' => $this->input->post('content'),
			'status' => 0,
			'createTime' => time(),
			'attribute' => $this->input->post('attribute'),
			'goodsMessage' => $_POST['goodsMessage'],
		];

		$this->stockOut_model->add($stockPut);
	}
}